<?php
 class Users extends CI_Model{
    function __construct(){
        parent::__construct();
    }
    
     /** 
     * Insert data for config
     * @author tien.nguyen
     */
    public function login($username, $password){
        $query = $this->db->get_where('users', array('UserName' => $username, 'Password' => $password));
        $user = $query->row();
        if($user){            
            if($password == $user->Password &&
                $user->Role == 'ADMIN'){
                //set session for user login
                foreach($user as $key => $value){
                    $this->session->set_userdata('admin_'.$key, $value);
                }
                return true;
            }
        }        
        return false;
    }  
    
 /**
     * Update user
     * @author tien.nguyen 
     */
    public function add($data){
        $data = $this->_convertData($data);
        return $this->db->insert('users', $data);
    }  
    
    /**
     * Update user
     * @author tien.nguyen 
     */
    public function edit($data, $userId){
        $data = $this->_convertData($data);
        if(empty($data['Password'])){
            unset($data['Password']);
        }
        return $this->db->update('users', $data, array('UserId' => $userId));
    }
    
    /**
     * Get user by user id
     * @author tien.nguyen
     */
    public function getUser($userId){
        $query = $this->db->get_where('users', array('UserId' => $userId));
        return $query->row_array(); 
    }
    
    /**
     * Get list user
     * @author get list user 
     */
    public function getListUsers($start = 0){
        $config = $this->config->item('pagination');
        
        $this->db->select();
        $this->db->from('users');
        $this->db->limit($config['number_row'], $start);
        $query = $this->db->get();
        return $query->result_array();
    }
    
    /**
     * Convert data array to array of product
     * @author tien.nguyen
     */
    private function _convertData($data){
        $res = array();
        $arr = array('UserId', 'UserName', 'Password', 
            'Enable', 'CreatedDate', 'Email', 'Phone',
            'Address', 'FullName', 'Role');
        foreach($arr as $item){
            if(isset($data[$item])){
                $res[$item] = $data[$item];
            }
        }
        
        //set default value
        $res['Enable'] = isset($res['Enable']) ? $res['Enable'] : 0;
        return $res;
    }
 }